﻿// -------------------------------------------------------------------------
//    @FileName         :    NFRobotModule.cpp
//    @Author           :    gaoyi
//    @Date             :   2023-07-10
//    @Email			:    445267987@qq.com
//    @Module           :    NFRobotModule.cpp
//
// -------------------------------------------------------------------------

#include "NFRobotModule.h"
#include "NFComm/NFCore/NFRandom.hpp"
#include "NFComm/NFCore/NFStringUtility.h"
#include "Scene/GameApi.h"

NFCRobotModule::NFCRobotModule(NFIPluginManager* p): NFIDynamicModule(p)
{
	std::string              param = p->GetStrParam();
	std::vector<std::string> vecParam;

	m_startId  = 10000;
	m_robotNum = 1;
	m_serverIp = "127.0.0.1";
	m_port     = 8013;
	NFStringUtility::SplitStringToVector(param, ",", vecParam);
	if (vecParam.size() >= 2)
	{
		m_startId  = NFCommon::strto<int>(vecParam[0]);
		m_robotNum = NFCommon::strto<int>(vecParam[1]);
	}
	if (vecParam.size() >= 3)
	{
		m_serverIp = vecParam[2];
	}
	if (vecParam.size() >= 4)
	{
		m_port = NFCommon::strto<int>(vecParam[3]);
	}
	m_robotIndex = m_startId;
}

NFCRobotModule::~NFCRobotModule()
{
}

int NFCRobotModule::Init()
{
	SetTimer(1, 1000);
	return 0;
}

GameApi* NFCRobotModule::CreateRobot()
{
	GameApi* pRobot = NF_NEW GameApi(m_pObjPluginManager);
	pRobot->Init(++m_robotIndex);

	m_robotMap.emplace((uint32_t)pRobot->m_iUid, pRobot);

	return pRobot;
}

uint64_t NFCRobotModule::GetRandRobotUserId()
{
	int i = NFRandomInt(0, m_robotUserIdList.size());
	if (i >= 0 && i < (int)m_robotUserIdList.size())
	{
		return m_robotUserIdList[i];
	}
	else if (m_robotUserIdList.size() > 0)
	{
		return m_robotUserIdList[0];
	}
	else
	{
		if ((int)m_robotMap.size() > 0)
		{
			return m_robotMap.begin()->second->m_ullLoginRoleID;
		}
	}

	return 0;
}

int NFCRobotModule::OnTimer(uint32_t nTimerID)
{
	static bool flag = false;
	if (!m_pObjPluginManager->IsInited(NF_ST_PROXY_SERVER))
	{
		return -1;
	}

	if (flag)
	{
		return 0;
	}

	flag = true;

	GameApi* pRobot = NF_NEW GameApi(m_pObjPluginManager);
	pRobot->Login(++m_robotIndex, 0, m_serverIp, m_port);

	m_robotMap.emplace((uint32_t)pRobot->m_iUid, pRobot);

	return 0;
}

int NFCRobotModule::Tick()
{
	return 0;
}

int NFCRobotModule::BeforeShut()
{
	return 0;
}

int NFCRobotModule::Shut()
{
	return 0;
}
